package com.jumi.microservice.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.constant.afterseal.AfterSealOrderStatusEnum;
import com.jumi.microservice.constant.compensation.AfterSaleEnum;
import com.jumi.microservice.constant.compensation.AfterSaleStatusEnum;
import com.jumi.microservice.constant.compensation.CheckStatusEnum;
import com.jumi.microservice.constant.compensation.LockFlagEnum;
import com.jumi.microservice.constant.refundgoods.CancelUserFlagEnum;
import com.jumi.microservice.constant.reissue.PostageTypeEnum;
import com.jumi.microservice.constant.reissue.ReissueStatusEnum;
import com.jumi.microservice.constant.reissue.ReissueTypeEnum;
import com.jumi.microservice.constant.reissue.SelfFlagEnum;
import com.jumi.microservice.dto.order.OrderLogRequest;
import com.jumi.microservice.dto.afterseal.AfterSealCancelRequest;
import com.jumi.microservice.dto.serviceDto.UpdateRefundInfoRequest;
import com.jumi.microservice.entity.AfterSealOrder;
import com.jumi.microservice.entity.Compensation;
import com.jumi.microservice.entity.Reissue;
import com.jumi.microservice.exception.AfterSealOrderExceptionEnum;
import com.jumi.microservice.mapper.AfterSealOrderMapper;
import com.jumi.microservice.mapper.CompensationMapper;
import com.jumi.microservice.mapper.ReissueMapper;
import com.jumi.microservice.service.IOrderDubboService;
import com.jumi.microservice.service.IOrderService;
import com.jumi.microservice.warehouseout.api.ApiSaledOrderWarehouseOutService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author scw
 * @date 2020/9/25
 */
@Service
public class AfterSealServiceImpl {
    @Resource
    private AfterSealOrderMapper afterSealOrderMapper;
    @Resource
    private ReissueMapper reissueMapper;
    @DubboReference
    private IOrderDubboService iOrderDubboService;
    @DubboReference
    private IOrderService iOrderService;
    @DubboReference
    ApiSaledOrderWarehouseOutService apiSaledOrderWarehouseOutService;
    @Resource
    private CompensationMapper compensationMapper;

    /**
     * 补发订单取消
     *
     * @param request
     * @return
     */
    @org.springframework.transaction.annotation.Transactional
    public Boolean cancelAfterSealOrder(AfterSealCancelRequest request) {
        Long operatorId = request.getOperatorId();
        String operatorName = request.getOperatorName();
        boolean res = false;
        int orderId = request.getId();
        //查询信息
        QueryWrapper<AfterSealOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderId);
        queryWrapper.eq("order_status", AfterSealOrderStatusEnum.ORDRE_STATUS_SHIP.getCode());
        queryWrapper.eq("order_type", request.getOrderType());
        AfterSealOrder afterSealOrder = afterSealOrderMapper.selectOne(queryWrapper);
        if (afterSealOrder == null) {
            throw new BaseException(AfterSealOrderExceptionEnum.INFO_NO_EXIST.getCode(), AfterSealOrderExceptionEnum.INFO_NO_EXIST.getMessage());
        }
        //取消订单
        afterSealOrder.setOrderStatus(AfterSealOrderStatusEnum.ORDRE_STATUS_CANCEL.getCode().byteValue());
        afterSealOrder.setCancelOperatorId(operatorId);
        afterSealOrder.setCancelOperatorName(operatorName);
        afterSealOrder.setCancelRemark(request.getCancelRemark());
        afterSealOrder.setCancelTime(new Date());
        if (afterSealOrderMapper.updateById(afterSealOrder) > 0) {
            Reissue reissue = reissueMapper.selectById(afterSealOrder.getReissueId());
            if (reissue != null) {
                //补发状态取消
                reissue.setCancelOperatorId(operatorId);
                reissue.setCancelOperatorName(operatorName);
                reissue.setStatus(ReissueStatusEnum.STATUS_CANCEL.getCode().byteValue());
                reissue.setCancelRemark(request.getCancelRemark());
                reissue.setCancelTime(new Date());
                if (reissueMapper.updateById(reissue) > 0) {
                    //自营商品
                    if (reissue.getSelfFlag() == SelfFlagEnum.SELF_FLAG_YES.getCode().byteValue()) {
                        /*
                         * 供应链取消售后订单
                         */
                        apiSaledOrderWarehouseOutService.cancelSaledOrderCode(reissue.getReissueOrderNo(), operatorName);
                    }
                    /*
                     * 更新订单商品表相关信息
                     */
                    int goodsNum = 0 - reissue.getGoodsNum();
                    UpdateRefundInfoRequest updateRefundInfoRequest = new UpdateRefundInfoRequest();
                    updateRefundInfoRequest.setOrderId(reissue.getOriginalOrderId());
                    updateRefundInfoRequest.setGoodsId(reissue.getGoodsId());
                    updateRefundInfoRequest.setReturnCount(goodsNum);
                    updateRefundInfoRequest.setReturnPrice(BigDecimal.valueOf(0));
                    updateRefundInfoRequest.setReturnPostage(BigDecimal.valueOf(0));
                    // <-2 不参与更新
                    updateRefundInfoRequest.setGoodsStatus((byte) -3);
                    updateRefundInfoRequest.setAfterSealStatus(AfterSaleStatusEnum.NORMAL.getCode().byteValue());
                    updateRefundInfoRequest.setRefundId(0);
                    iOrderService.updateRefundInfo(updateRefundInfoRequest);
                    //换货
                    if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_REPLACE.getCode().byteValue()) {
                        /*
                         * 补偿邮费
                         * 默认锁定执行解锁操作
                         * 是否锁定: 0-否 1-是
                         */
                        QueryWrapper<Compensation> queryWrapperCompensation = new QueryWrapper<>();
                        queryWrapperCompensation.eq("refund_id", reissue.getId());
                        queryWrapperCompensation.eq("after_sale_type", AfterSaleEnum.AFTER_SALE_BCYF.getCode());
                        queryWrapperCompensation.eq("postage_type", PostageTypeEnum.POSTAGE_TYPE_REISSUE.getCode());
                        queryWrapperCompensation.eq("check_status", CheckStatusEnum.CHECK_STATUS_WAIT.getCode());
                        queryWrapperCompensation.eq("original_order_id", reissue.getOriginalOrderId());
                        queryWrapperCompensation.eq("compensation_goods_id", reissue.getGoodsId());
                        queryWrapperCompensation.eq("buyer_id", reissue.getBuyerId());
                        queryWrapperCompensation.orderByDesc("id");
                        queryWrapperCompensation.last("limit 1");
                        Compensation compensation = compensationMapper.selectOne(queryWrapperCompensation);
                        if (compensation != null) {
                            compensation.setCheckStatus(CheckStatusEnum.CHECK_STATUS_REFUSE.getCode().byteValue());
                            compensation.setCheckTime(new Date());
                            compensation.setCheckOperatorId(operatorId);
                            compensation.setCheckOperatorName(operatorName);
                            compensation.setCheckRemark("售后处理-取消换货订单");
                            compensationMapper.updateById(compensation);
                        }
                    }
                }

                /*
                 * 操作日志表插入相关信息
                 * 售后订单
                 */
                String logInfo = "售后处理--取消";
                if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_GOODS.getCode().byteValue()) {
                    logInfo += "补发";
                } else if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_MISSED.getCode().byteValue()) {
                    logInfo += "补发漏发";
                } else {
                    logInfo += "换货";
                }
                logInfo += "订单";
                //用户标识，1 前端用户， 2 后端管理员
                Byte userFlag = CancelUserFlagEnum.USER_FLAG_ADMIN.getCode().byteValue();
                OrderLogRequest orderLogRequest = new OrderLogRequest();
                orderLogRequest.setLog(logInfo);
                orderLogRequest.setOperatorId(operatorId);
                orderLogRequest.setOperatorName(operatorName);
                orderLogRequest.setUserFlag(userFlag);
                orderLogRequest.setOrderSn(afterSealOrder.getOrderNo());
                iOrderDubboService.addOrderLog(orderLogRequest);

                /*
                 * 操作日志表插入相关信息
                 * 原始订单
                 */
                String logInfo2 = "售后处理--售后订单--取消";
                if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_GOODS.getCode().byteValue()) {
                    logInfo2 += "补发";
                } else if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_MISSED.getCode().byteValue()) {
                    logInfo2 += "补发漏发";
                } else {
                    logInfo2 += "换货";
                }
                //用户标识，1 前端用户， 2 后端管理员
                Byte userFlag2 = CancelUserFlagEnum.USER_FLAG_ADMIN.getCode().byteValue();
                OrderLogRequest orderLogRequest2 = new OrderLogRequest();
                orderLogRequest2.setLog(logInfo2);
                orderLogRequest2.setOperatorId(operatorId);
                orderLogRequest2.setOperatorName(operatorName);
                orderLogRequest2.setUserFlag(userFlag2);
                orderLogRequest2.setOrderSn(afterSealOrder.getOriginalOrderNo());
                iOrderDubboService.addOrderLog(orderLogRequest2);
                res = true;
            }
        }
        return res;
    }
}
